import Vue from 'vue'
import VueRouter from 'vue-router'

// 引入 store 寻找 token
import store from '@/store'

// 导入相应组件
import Login from '@/views/Login'
import Home from '@/views/Layout/home'
import Layout from '@/views/Layout'

// 引入后台主页组件

// 需要页面懒加载
// import UserInfo from '@/views/Layout/User/UserInfo.vue'
const UserInfo = () => import('@/views/Layout/User/UserInfo.vue')
// import Register from '@/views/Register'
const Register = () => import('@/views/Register')
// import UserAvatar from '@/views/Layout/User/UserAvatar.vue'
const UserAvatar = () => import('@/views/Layout/User/UserAvatar.vue')
// import UserPwd from '@/views/Layout/User/UserPwd.vue'
const UserPwd = () => import('@/views/Layout/User/UserPwd.vue')
// import ArtiCle from '@/views/Layout/Article/ArtiCle.vue'
const ArtiCle = () => import('@/views/Layout/Article/ArtiCle.vue')
// import ArtList from '@/views/Layout/Article/ArtList.vue'
const ArtList = () => import('@/views/Layout/Article/ArtList.vue')
// import _404 from '@/views/404/404.vue'
const _404 = () => import('@/views/404/404.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login, meta: { title: '登陆页' } },
  { path: '/register', component: Register, meta: { title: '登陆页' } },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    children: [
      { path: 'home', component: Home, meta: { title: '登陆页' } },
      { path: 'user-info', component: UserInfo, meta: { title: '基本资料' } },
      { path: 'user-Avatar', component: UserAvatar, meta: { title: '更换头像' } },
      { path: 'user-pwd', component: UserPwd, meta: { title: '重置密码' } },
      { path: 'art-cate', component: ArtiCle, meta: { title: '文章分类' } },
      { path: 'art-list', component: ArtList, meta: { title: '文章列表' } }
    ],
    meta: { title: '首页' }
  },
  // 配置 404 页面
  { path: '*', component: _404 }
]

const router = new VueRouter({
  routes
})

// src/router/index.js 路由模块
Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}

// 路由的全局守卫
// 设置白名单
const whiteList = ['/login', '/register']
router.beforeEach((to, form, next) => {
  const { token } = store.state.user
  document.title = to.meta.title
  if (token) {
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
